#!/usr/bin/env python
#  -*- coding: utf-8 -*-
# FileName: maillogging.py
# ModuleName: maillogging
# Description: 邮件记录模块，将应用程序中的记录通过
#              邮件发送。
# Author: PZX
# creating time: 2011-10-11 20:33:42
# modified time: 2011-10-12 10:19:35

# 导入相关库
import logging
import logging.handlers

# 
class SMTPAuthHandler(logging.handlers.SMTPHandler):
    def __init__(self, mailhost, fromaddr, toaddrs, subject, username='', passwd='', needAuth=False):
        """
        initialization function.
                  
                        调用基类的构造函数，并且对username以及passwd变量复制
        mailhost:SMTP主机
        fromaddr:放送方邮件地址
        toaddrs:接收方邮件地址，list类型
        subject:邮件主题
        username:SMTP帐号
        passwd:SMTP密码
        needAuth:是否登录授权
        """
        #调用基类构造函数
        logging.handlers.SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject)
        #给username，passwd和needAuth赋值
        self.username = username
        self.passwd = passwd
        self.needAuth = needAuth
        
    def emit(self, record):
        """
        Emit a record.
    
        
        Overriding the emit function of base class.Add authorization module
        Format the record and send it to the specified addressees.
        recode:需要发送的信息
        """
        try:
            import smtplib
            import string
            try:
                from email.Utils import formatdate
            except:
                formatdate = self.date_time
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                self.fromaddr, 
                string.join(self.toaddrs, ","), 
                self.getSubject(record), 
                formatdate(), msg)
            #登录需要授权的服务器
            if self.needAuth:
                smtp.login(self.username, self.passwd)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

def getMySMTPAuthLogger(loggerName, level):
    """
    get the SMTPAuth logger.
    
    get a logger with name of loggerName and SMTPAuthHandler
    loggerName: logger's name
    level: logging level
    """
    #creating the formatter
    formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', 
                                  '%Y %m-%d %H:%M')
    #new a SMTPAuthHandler
    smtpAuthHandler = SMTPAuthHandler('smtp.qq.com', 'yourmail@yourdomain.com', ['yourmail@yourdomain.com'],
                                      'just test for smtp module',
                                      'yourmail@yourdomain.com', 'yourpasswd', True)
    #set the logging level
    smtpAuthHandler.setLevel(level)
    #set the logging formatter
    smtpAuthHandler.setFormatter(formatter)
    #get the logger of the specified name
    logger = logging.getLogger(loggerName)
    #set the logger level
    logger.setLevel(level)
    #add the SMTPAuthHandler for the logger
    logger.addHandler(smtpAuthHandler)
    return logger
    
def test():
    """
    test the module.
    """
    smtpAuthLogger = getMySMTPAuthLogger('test', logging.DEBUG)
    smtpAuthLogger.info('this is a logging message for testing this module')
    print 'test end'

if __name__ == '__main__':
    test()